package com.warrantyhotel.android.service;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;

import com.warrantyhotel.android.R;
import com.warrantyhotel.android.db.QueriesCodes;
import com.warrantyhotel.android.db.WarrantyHotelDBSchema.News_RSS;
import com.warrantyhotel.android.model.Keys;
import com.warrantyhotel.android.model.RssNewsNotifyObject;
import com.warrantyhotel.android.ui.NewsActivityDetail;
import com.warrantyhotel.android.util.DetachableResultReceiver;
import com.warrantyhotel.android.util.DetachableResultReceiver.Receiver;

public class UpdateNewsServise extends Service implements Receiver {

	private Timer timer;
	private UpdateTimeTask updateTimertask;
	private static final int UPDATE_NEWS = 2;
	private DetachableResultReceiver receiver;
	private static SharedPreferences prefs;

	class UpdateTimeTask extends TimerTask {
		public void run() {
			handler.sendEmptyMessage(UPDATE_NEWS);
		}
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		receiver = new DetachableResultReceiver(new Handler());
		receiver.setReceiver(this);
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
		if (updateTimertask != null) {
			updateTimertask.cancel();
		}
		if (timer != null) {
			timer.cancel();
		}
		timer = new Timer();
		updateTimertask = new UpdateTimeTask();
		timer.schedule(updateTimertask, 10, 2 * 60 * 60 * 1000);
		super.onStart(intent, startId);

	}

	@Override
	public boolean onUnbind(Intent intent) {
		return super.onUnbind(intent);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (updateTimertask != null) {
			updateTimertask.cancel();
		}
		if (timer != null) {
			timer.cancel();
		}
	}

	Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case UPDATE_NEWS:
				loginBefore();
				updateNews();
				break;

			}
		};
	};

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {
		switch (resultCode) {
		case UpdateIntentService.STATUS_RUNNING:
			break;
		case UpdateIntentService.STATUS_ERROR:
			break;
		case UpdateIntentService.STATUS_FINISHED:
			ArrayList<RssNewsNotifyObject> rssNews = resultData.getParcelableArrayList(Keys.rssNewsNotif);
			updateNewsOnRssActivity();
			updateInbox();
			for (int i = 0; i < rssNews.size(); i++) {
				RssNewsNotifyObject item = rssNews.get(i);
				showNotification(item.getGuid(), item.getTitle(), item.getDescription(), i);
			}

			break;
		}

	}

	private void updateInbox() {

		Intent testIntent = new Intent(Intent.ACTION_SYNC, null, this, UpdateIntentService.class);
		testIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.INBOX);
		startService(testIntent);

	}

	private void updateNewsOnRssActivity() {
		Intent userInfoIntent = new Intent(Intent.ACTION_SYNC, News_RSS.CONTENT_URI, this, UpdateIntentService.class);
		userInfoIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.NEWS_RSS);
		startService(userInfoIntent);

	}

	private void updateNews() {
		Intent testIntent = new Intent(Intent.ACTION_SYNC, null, UpdateNewsServise.this, UpdateIntentService.class);
		testIntent.putExtra(UpdateIntentService.EXTRA_STATUS_RECEIVER, receiver);
		testIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.RSS_NOTIFICATION);
		startService(testIntent);
	}

	private void loginBefore() {

		Intent loginIntent = new Intent(Intent.ACTION_SYNC, null, this, UpdateIntentService.class);
		loginIntent.putExtra(UpdateIntentService.EXTRA_REQUEST_CODE, QueriesCodes.DO_LOGIN);
		loginIntent.putExtra(Keys._username, prefs.getString(Keys._cacheLogin, ""));
		loginIntent.putExtra(Keys._password, prefs.getString(Keys._cachePass, ""));
		loginIntent.putExtra(Keys._remembeMe, true);
		startService(loginIntent);

	}

	protected void showNotification(String guid, String title, String description, int id) {

		NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

		CharSequence from = title;
		CharSequence message = description;

		Intent intent = new Intent(getApplicationContext(), NewsActivityDetail.class);
		intent.putExtra(Keys._guid, guid);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);

		String tickerText = "Warranty Hotel News";

		Notification notif = new Notification(R.drawable.icon_warranty, tickerText, System.currentTimeMillis());
		notif.flags |= Notification.FLAG_AUTO_CANCEL;
		notif.setLatestEventInfo(this, from, message, contentIntent);

		notif.vibrate = new long[] { 0, 250, 100, 500 };

		nm.notify("Warranty Hotel News", id, notif);
	}

}
